const express = require("express");
// 跨域中间件
const cors = require("cors");

// 请求参数解析中间件
const bodyParser = require("body-parser");
// 处理文件中间件
const multer = require("multer");

const app = express()

// 挂在全局错误提示的中间件

app.use((req, res, next) => {


    res.errFunc = (err, status = 1) => {
        res.send({
            status,
            error: err instanceof Error ? err.message : err
        })
    }
    next();
})

app.use(cors());

app.use(express.static("./public"))

const uploadFile = multer({
    dest: "./public/upload"
})

app.use(uploadFile.any())

/**
 * 解析  application/x-www-form-urlencoded
 * extenden为false时，值为字符串或数组，为true时，值为任意类型
*/
app.use(bodyParser.urlencoded({ extended: false }));


// 解析 application/json数据
app.use(bodyParser.json());


const { expressjwt: jwt } = require("express-jwt");
const jwtConfig = require("./jwt-config");

app.use(jwt({ secret: jwtConfig.jwtSecretKey, algorithms: ["HS256"] }).unless({ path: [/^\/api/] }))


const loginRouter = require("./router/login");

app.use("/api", loginRouter);

const userRouter = require("./router/user.js");

app.use("/user", userRouter)


const Joi = require("joi");

app.use((err, req, res, next) => {
    if (err instanceof Joi.ValidationError) {
        res.errFunc(err)
    }
    if (err) {
        res.errFunc(err)
    }
    next();
})

app.listen(3007, () => {
    console.log("the server is started on 3007")
})